<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Fall Detection Control Panel</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            line-height: 1.6;
            margin: 0;
            padding: 20px;
            background-color: #f4f4f4;
        }
        .container {
            max-width: 800px;
            margin: auto;
            background: white;
            padding: 20px;
            border-radius: 5px;
            box-shadow: 0 0 10px rgba(0,0,0,0.1);
        }
        .section {
            margin-bottom: 20px;
            padding: 10px;
            background-color: #f9f9f9;
            border-radius: 5px;
        }
        h1, h2 {
            color: #333;
        }
        input, select, button {
            margin: 5px 0;
            padding: 5px;
        }
        button {
            background-color: #4CAF50;
            color: white;
            border: none;
            padding: 10px 15px;
            cursor: pointer;
        }
        button:hover {
            background-color: #45a049;
        }
        button:disabled {
            background-color: #cccccc;
            cursor: not-allowed;
        }
        #cameraList {
            margin-top: 10px;
        }
        textarea {
            width: 100%;
            margin-top: 10px;
        }
        .error {
            color: red;
            margin-top: 5px;
        }
        .success {
            color: green;
            margin-top: 5px;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>Fall Detection Control Panel</h1>
        
        <div class="section">
            <h2>Add Camera</h2>
            <input type="text" id="cameraId" placeholder="Camera ID">
            <input type="text" id="rtmpUrl" placeholder="RTMP URL">
            <input type="text" id="pushUrl" placeholder="Push URL">
            <button id="addCameraBtn" onclick="addCamera()">Add Camera</button>
            <div id="addCameraMessage"></div>
        </div>

        <div class="section">
            <h2>Camera List</h2>
            <button id="refreshCamerasBtn" onclick="getCameras()">Refresh Camera List</button>
            <div id="cameraList"></div>
        </div>

        <div class="section">
            <h2>Camera Control</h2>
            <select id="cameraSelect"></select>
            <button onclick="controlCamera('start_process')">Start Processing</button>
            <button onclick="controlCamera('stop_process')">Stop Processing</button>
            <button onclick="controlCamera('start_stream')">Start Streaming</button>
            <button onclick="controlCamera('stop_stream')">Stop Streaming</button>
            <div id="cameraControlMessage"></div>
        </div>

        <div class="section">
            <h2>Configuration</h2>
            <textarea id="configArea" rows="10" cols="50"></textarea>
            <button onclick="getConfig()">Get Config</button>
            <button onclick="updateConfig()">Update Config</button>
            <div id="configMessage"></div>
        </div>
    </div>

    <script>
        const API_URL = 'http://127.0.0.1:5000/api/falldetect';

        async function fetchWithNgrokHeader(url, options = {}) {
            const ngrokOptions = {
                ...options,
                headers: {
                    ...options.headers,
                    'ngrok-skip-browser-warning': 'true'
                }
            };
            const response = await fetch(url, ngrokOptions);
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            return response;
        }

        async function addCamera() {
            const cameraId = document.getElementById('cameraId').value;
            const rtmpUrl = document.getElementById('rtmpUrl').value;
            const pushUrl = document.getElementById('pushUrl').value;
            const messageElement = document.getElementById('addCameraMessage');
            const addButton = document.getElementById('addCameraBtn');

            addButton.disabled = true;
            messageElement.textContent = 'Adding camera...';
            messageElement.className = '';

            try {
                const response = await fetchWithNgrokHeader(`${API_URL}/add_camera`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        cameras: [{ camera_id: cameraId, rtmp_url: rtmpUrl, push_url: pushUrl }]
                    }),
                });

                const data = await response.json();
                messageElement.textContent = data.message;
                messageElement.className = 'success';
                getCameras();
            } catch (error) {
                console.error('Error:', error);
                messageElement.textContent = `Failed to add camera: ${error.message}`;
                messageElement.className = 'error';
            } finally {
                addButton.disabled = false;
            }
        }

        async function getCameras() {
            const cameraList = document.getElementById('cameraList');
            const cameraSelect = document.getElementById('cameraSelect');
            const refreshButton = document.getElementById('refreshCamerasBtn');

            refreshButton.disabled = true;
            cameraList.innerHTML = 'Loading cameras...';
            cameraSelect.innerHTML = '';

            try {
                const response = await fetchWithNgrokHeader(`${API_URL}/get_cameras`);
                const data = await response.json();
                
                cameraList.innerHTML = '';
                cameraSelect.innerHTML = '';

                for (const [id, info] of Object.entries(data)) {
                    cameraList.innerHTML += `<p>${id}: ${info.rtmp_url} -> ${info.push_url}</p>`;
                    cameraSelect.innerHTML += `<option value="${id}">${id}</option>`;
                }

                if (Object.keys(data).length === 0) {
                    cameraList.innerHTML = 'No cameras found.';
                }
            } catch (error) {
                console.error('Error:', error);
                cameraList.innerHTML = `Failed to get cameras: ${error.message}`;
                cameraList.className = 'error';
            } finally {
                refreshButton.disabled = false;
            }
        }

        async function controlCamera(action) {
            const cameraId = document.getElementById('cameraSelect').value;
            const messageElement = document.getElementById('cameraControlMessage');

            messageElement.textContent = `Processing ${action}...`;
            messageElement.className = '';

            try {
                const response = await fetchWithNgrokHeader(`${API_URL}/${cameraId}/${action}`, { method: 'POST' });
                const data = await response.json();
                messageElement.textContent = data.status;
                messageElement.className = 'success';
            } catch (error) {
                console.error('Error:', error);
                messageElement.textContent = `Failed to ${action}: ${error.message}`;
                messageElement.className = 'error';
            }
        }

        async function getConfig() {
            const configArea = document.getElementById('configArea');
            const messageElement = document.getElementById('configMessage');

            messageElement.textContent = 'Loading configuration...';
            messageElement.className = '';

            try {
                const response = await fetchWithNgrokHeader(`${API_URL}/config`);
                const data = await response.json();
                configArea.value = JSON.stringify(data, null, 2);
                messageElement.textContent = 'Configuration loaded successfully';
                messageElement.className = 'success';
            } catch (error) {
                console.error('Error:', error);
                messageElement.textContent = `Failed to get config: ${error.message}`;
                messageElement.className = 'error';
            }
        }

        async function updateConfig() {
            const configArea = document.getElementById('configArea');
            const messageElement = document.getElementById('configMessage');

            messageElement.textContent = 'Updating configuration...';
            messageElement.className = '';

            try {
                const config = JSON.parse(configArea.value);
                const response = await fetchWithNgrokHeader(`${API_URL}/config`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify(config),
                });

                const data = await response.json();
                messageElement.textContent = data.message;
                messageElement.className = 'success';
            } catch (error) {
                console.error('Error:', error);
                messageElement.textContent = `Failed to update config: ${error.message}`;
                messageElement.className = 'error';
            }
        }

        // 初始加载摄像头列表
        getCameras();
    </script>
</body>
</html>